package math;

import org.junit.Test;

import java.util.Arrays;

public class AddStrings415 {
    @Test
    public void test1() {
        addStrings("11", "123");
        addStrings("456", "77");
        addStrings("0", "0");
    }

    public String addStrings(String s1, String s2) {
        int[] n1 = toIntArrayReversed(s1);
        int[] n2 = toIntArrayReversed(s2);

        // makes n1 the longer one
        if (n1.length < n2.length) {
            int[] t = n1;
            n1 = n2;
            n2 =t;
        }

        int[] r = new int[n1.length+1];
        Arrays.fill(r, 0);
        int i;
        for (i = 0; i < n2.length; i++) {
            r[i] = r[i] + n1[i] + n2[i];
            if (r[i] >= 10) {
                r[i+1] = 1;
                r[i] -= 10;
            }
        }

        for (; i< n1.length; i++) {
            r[i] = r[i] + n1[i];
            if (r[i] >= 10) {
                r[i+1] = 1;
                r[i] -= 10;
            }
        }

        int j = r.length - 1;
        while (j >= 0 && r[j] == 0) {
            j--;
        }

        if (j < 0) {
            System.out.format("s1: %s, s2: %s: result: %s\n", s1, s2, "0");
            return "0";
        }
        char[] c = new char[j+1];
        for (; j >= 0; j--) {
            c[c.length-j-1] = (char)(r[j] + '0');
        }
        String result = new String(c);
        System.out.format("s1: %s, s2: %s: result: %s\n", s1, s2, result);
        return result;
    }

    // "12345" -> [5,4,3,2,1]
    public int[] toIntArrayReversed(String s) {
        int[] n = new int[s.length()];
        for (int i = 0; i < s.length(); i++) {
            n[i] = s.charAt(s.length()-i-1) - '0';
        }
        return n;
    }
}
